package com.linkface.liveness.network;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Copyright (c) 2017-2018 LINKFACE Corporation. All rights reserved.
 */

public class LFGetRequestUtils {

    public static final String TAG = LFGetRequestUtils.class.getSimpleName();


    public static void getRequest(String getUrl, LFNetRequestCallback callback) {
        getSyn(getUrl, callback);
    }

    public static void getSyn(String url, final LFNetRequestCallback callback) {

        OkHttpClient okHttpClient;

        OkHttpClient.Builder okhttpBuilder = new OkHttpClient.Builder();
        okhttpBuilder.connectTimeout(20, TimeUnit.SECONDS);
        okhttpBuilder.writeTimeout(20, TimeUnit.SECONDS);
        okhttpBuilder.readTimeout(20, TimeUnit.SECONDS);
        okHttpClient = okhttpBuilder.build();

        if (url == null || "".equals(url)) {
            sendFailResult(callback, 404, "URL无效");
            return;
        }
        Request.Builder builder = new Request.Builder();

        try {
            builder.url(url);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        final Request request = builder.build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                sendFailResult(callback, 404, "网络请求失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                dealRequestResponse(response, callback);
            }
        });
    }

    private static void dealRequestResponse(Response response, final LFNetRequestCallback callback) throws IOException {
        if (response != null) {
            int code = response.code();
            if (code == 200) {
                String result = response.body().string();
                if (result != null) {
                    sendSuccessResult(callback, result);
                } else {
                    sendFailResult(callback, 0, "");
                }
            } else {
                String result = response.body().string();
                sendFailResult(callback, code, response.message());
            }
        } else {
            sendFailResult(callback, 0, "");
        }
    }

    public static <T> void sendFailResult(final LFNetRequestCallback callback, final int errorCode, final String errorString) {
        if (callback != null) {
            callback.failed(errorCode, errorString);
        }
    }

    public static void sendSuccessResult(final LFNetRequestCallback callback, final String response) {

        if (callback != null) {
            callback.completed(response);
        }
    }
}
